package org.example.springbootrabbitmq;

import lombok.extern.slf4j.Slf4j;
import org.example.springbootrabbitmq.delayed.DelayedQueueConfig;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@RestController
@RequestMapping("/ttl")
@Slf4j
public class TtlController {

    @Autowired
    private RabbitTemplate rabbitTemplate;
    @RequestMapping("/sendMsg/{message}")
    public String sendMsg(@PathVariable String message) {
        log.info("send message:{}", message);
        rabbitTemplate.convertAndSend("X", "XA", message);
        rabbitTemplate.convertAndSend("X", "XB", message);
        return "send";
    }

    /**
     * 手写死信队列实现消息延迟优化
     * 业务侧给消息设置过期时间
     * @param message 消息体
     * @param ttlTime 延时时间
     * @return 消息内容
     */
    @RequestMapping("/sendMsg/{message}/{ttlTime}")
    public void sendMsg(@PathVariable String message, @PathVariable String ttlTime) {
        log.info("当前时间：{},发送消息的时长：{}毫秒ttl消息给QC队列,", new Date(), ttlTime);
        rabbitTemplate.convertAndSend("X","XC",message, messages -> {
            messages.getMessageProperties().setExpiration(ttlTime);
            return messages;
        });
    }

    /**
     * 真实场景延迟队列发送消息
     * @param message
     * @param delayTime
     */
    @RequestMapping("/sendDelayMsg/{message}/{delayTime}")
    public void sendDelayMsg(@PathVariable String message, @PathVariable Integer delayTime) {
        log.info("当前时间：{},发送消息的时长：{}毫秒ttl消息给延迟队列队列,消息体：,{}", new Date(), delayTime,message);
        rabbitTemplate.convertAndSend(DelayedQueueConfig.DELAYED_EXCHANGE,DelayedQueueConfig.DELAYED_ROUTING_KEY,message, messages -> {
            messages.getMessageProperties().setDelay(delayTime);
            return messages;
        });
    }
}
